import _ from 'lodash';
import * as api from '@/services/PriceMgr';
import * as utils from '../utils/treeUtils';

const Model = {
  namespace: 'PriceManageItems',
  state: {
    all: [],
    searched: [],
    expandedRowKeys: [],
    searchItems: {},
    query: {},
    versionDetail: {},
    ptBatchData: [],
    initPtBatchData: [],
  },
  effects: {
    *init({ payload, callback }, { call, put }) {
      yield put({
        type: 'clear',
      });
      const response = yield call(api.getPriceVersionUsingGET, payload);
      if (response && response.data && !_.isEmpty(response.data.items)) {
        let all = response.data.items;
        const { versionDetail } = response.data;
        const isMarketing = versionDetail.isMarket === 'market';
        const category =
          payload.category === 'dynamic' ? versionDetail.versionAccountStage : payload.category;
        const params = {
          ...payload,
          isMarketing,
          category,
        };
        all = _.filter(
          all,
          item =>
            !item.businessTypeName ||
            item.businessTypeName === '可售' ||
            item.businessTypeName === '阶段性自持',
        );
        // 格式化每行
        all = utils.generateRowStructure(all, params);
        // 重新 待拆（其它）面积段节点、未推售车位节点
        all = utils.recalculateParentNodes(all, params);
        // 计算验证需要的字段
        all = utils.calculateValidateOptions(all, params);

        all = _.filter(all, item => !(item.isNew === true && item.isDeleted === true));

        const allCopy = _.cloneDeep(all);
        const canSave = utils.canSave(allCopy);
        const filteredAll = _.filter(all, item => !(item.isDeleted === true));
        const searched = utils.getCalculatedTree(filteredAll, params);

        // 未构成tree之前拿出搜索项
        const searchItems = utils.getSearchItems(filteredAll);
        // 获取展开的列key
        const expandedRowKeys = utils.getExpandedRowKeys(all);
        // 这里会改变all
        //  重新算其它的时候   一开始需要重新算其它吗  需要
        yield put({
          type: 'save',
          payload: {
            isMarketing,
            canSave,
            versionDetail,
            all: allCopy,
            searched,
            expandedRowKeys,
            query: {},
            searchItems,
            ptBatchData: utils.getItemRows(searched),
            initPtBatchData: utils.getItemRows(searched),
          },
        });
      }
      if (callback) callback();
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    clear() {
      return {
        all: [],
        searched: [],
        expandedRowKeys: [],
        searchItems: {},
        query: {},
      };
    },
    saveQuery(state, action) {
      let all = _.cloneDeep(state.all);
      const { isMarketing, versionDetail } = state;
      const category =
        action.payload.category === 'dynamic'
          ? versionDetail.versionAccountStage
          : action.payload.category;
      const params = {
        ...action.payload,
        isMarketing,
        category,
      };
      const { query } = action.payload;
      if (!utils.isObjectEmpty(query)) {
        all = _.filter(all, item => !(item.isNew === true && item.isDeleted === true));
        // 格式化每行
        all = utils.generateRowStructure(all, params);
        all = utils.buildSearchPath(all, '0', null);

        if (query && !_.isEmpty(query) && query !== 'undefined' && query !== undefined) {
          all = utils.filterAll({ all, query });
        }
        all = _.filter(all, item => !(item.isDeleted === true));
      }

      // params.isQuery = true;
      const searched = utils.getCalculatedTree(all, params);
      // 获取展开的列key
      const expandedRowKeys = utils.getExpandedRowKeys(all);
      return {
        ...state,
        query,
        searched,
        expandedRowKeys,
      };
    },
    saveRows(state, action) {
      let rowDatas = action.payload.rowData;
      let { all, versionDetail } = state;
      const isMarketing = state.versionDetail.isMarket === 'market';
      const category =
        action.payload.category === 'dynamic'
          ? versionDetail.versionAccountStage
          : action.payload.category;
      const params = {
        ...action.payload,
        isMarketing,
        category,
      };
      all = _.cloneDeep(all);

      if (!_.isArray(rowDatas)) {
        rowDatas = [rowDatas];
      }

      rowDatas.forEach(element => {
        const rowData = element;
        if (rowData.isAdd) {
          delete rowData.isAdd;
          rowData.isNew = true;
          all.push(rowData);
        } else {
          if (rowData.isRemove) {
            delete rowData.isRemove;
            rowData.isDeleted = true;
          }
          all.forEach((item, i) => {
            if (item.id === rowData.id) {
              all[i] = rowData;
            }
          });
        }
      });

      all = _.filter(all, item => !(item.isNew === true && item.isDeleted === true));
      // 格式化每行
      all = utils.generateRowStructure(all, params);
      // 重新 待拆（其它）面积段节点、未推售车位节点
      all = utils.recalculateParentNodes(all, params);
      // 计算验证需要的字段
      all = utils.calculateValidateOptions(all, params);

      const allCopy = _.cloneDeep(all);
      all = _.filter(all, item => !(item.isDeleted === true));
      const canSave = utils.canSave(all);
      const searched = utils.getCalculatedTree(all, params);
      // 获取展开的列key
      const expandedRowKeys = utils.getExpandedRowKeys(all);
      return {
        ...state,
        canSave,
        all: allCopy,
        searched,
        expandedRowKeys,
        initPtBatchData: utils.getItemRows(searched),
        ptBatchData: utils.getItemRows(searched),
      };
    },
    // 批量修改普调
    changeBatchModifyPt(state, action) {
      const { val, ids } = action.payload;
      const data = state.ptBatchData;
      const newData = data.map(item => {
        const setItem = _.cloneDeep(item);
        ids.forEach(id => {
          if (item.id === id) {
            const afterPrice = Number(item.beforePrice) + item.beforePrice * (val / 100);
            setItem.afterPrice = afterPrice;
            setItem.range = val;
            if (item.rows.isParking === 1) {
              setItem.rows.averagePrice_parking = afterPrice;
            }
            if (item.rows.isParking === 0) {
              setItem.rows.averagePrice_house = afterPrice;
            }
          }
        });
        return setItem;
      });
      return {
        ...state,
        ptBatchData: newData,
      };
    },
    // 批量修改普调保存
    saveBatchModifyPt(state, action) {
      const { all, ptBatchData, versionDetail } = state;
      const params = {
        ...action.payload,
        isMarketing: versionDetail.isMarket === 'market',
        category: versionDetail.versionAccountStage,
      };
      let cloneAll = _.cloneDeep(all);

      const getCheckedRows = _.cloneDeep(ptBatchData).map(row => row.rows);

      const allRows = [];
      getCheckedRows.forEach(item => {
        allRows.push(item);
        if (item?.children && !_.isEmpty(item.children)) {
          item.children.forEach(nootItem => {
            const setNootItem = nootItem;
            if (nootItem.isParking) {
              setNootItem.averagePrice_parking = item.averagePrice_parking;
            } else {
              setNootItem.averagePrice_house = item.averagePrice_house;
            }
          });
          allRows.push(...item.children);
        }
      });

      allRows.forEach(element => {
        const rowData = element;
        if (rowData.isAdd) {
          delete rowData.isAdd;
          rowData.isNew = true;
          cloneAll.push(rowData);
        } else {
          if (rowData.isRemove) {
            delete rowData.isRemove;
            rowData.isDeleted = true;
          }
          cloneAll.forEach((item, i) => {
            if (item.id === rowData.id) {
              cloneAll[i] = rowData;
            }
          });
        }
      });
      cloneAll = _.filter(cloneAll, item => !(item.isNew === true && item.isDeleted === true));
      // 格式化每行
      cloneAll = utils.generateRowStructure(cloneAll, params);
      // 重新 待拆（其它）面积段节点、未推售车位节点
      cloneAll = utils.recalculateParentNodes(cloneAll, params);
      // 计算验证需要的字段
      cloneAll = utils.calculateValidateOptions(cloneAll, params);

      const allCopy = _.cloneDeep(cloneAll);
      cloneAll = _.filter(cloneAll, item => !(item.isDeleted === true));
      const canSave = utils.canSave(cloneAll);
      const searched = utils.getCalculatedTree(cloneAll, params);
      // 获取展开的列key
      const expandedRowKeys = utils.getExpandedRowKeys(cloneAll);
      return {
        ...state,
        canSave,
        all: allCopy,
        searched,
        expandedRowKeys,
        initPtBatchData: ptBatchData,
      };
    },
  },
};
export default Model;
